<template>
  <div class="change-password-container">
    <h1>修改密码</h1>
    <form @submit.prevent="changePassword">
      <div class="form-group">
        <label for="oldPassword">旧密码</label>
        <input type="password" id="oldPassword" v-model="oldPassword" required />
      </div>
      <div class="form-group">
        <label for="newPassword">新密码</label>
        <input type="password" id="newPassword" v-model="newPassword" required />
      </div>
      <div class="form-group">
        <label for="confirmPassword">确认新密码</label>
        <input type="password" id="confirmPassword" v-model="confirmPassword" required />
      </div>
      <div v-if="error" class="error-message">{{ error }}</div>
      <button type="submit" class="submit-button">修改密码</button>
    </form>
  </div>
</template>
<script setup>
import { ref } from 'vue';
import axios from 'axios';
import {ElMessage} from "element-plus";
import router from "@/router";
const user = ref(getUser());

// 定义表单数据
const oldPassword = ref('');
const newPassword = ref('');
const confirmPassword = ref('');


// 提交表单的方法
const changePassword = () => {
  if (newPassword.value !== confirmPassword.value) {
     ElMessage.error('新密码和确认密码不一致');
    return;
  }

  axios.post(BASEURL+'/common/change-password', {
    username : user.value.username,
    oldPassword: oldPassword.value,
    newPassword: newPassword.value
  })
      .then(response => {
        if (response.data.code===2000) {
         ElMessage.success('密码修改成功');
          // 清空表单
          oldPassword.value = '';
          newPassword.value = '';
          confirmPassword.value = '';
          router.push('/login')
        } else {
          ElMessage.error('旧密码错误，请重新输入');
          oldPassword.value = '';
          newPassword.value = '';
          confirmPassword.value = '';
        }
      });
};
</script>


<style scoped>
.change-password-container {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  max-width: 400px;
  margin: 0 auto;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.error-message {
  color: red;
  margin-bottom: 15px;
}

.submit-button {
  padding: 10px 20px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  width: 100%;
}

.submit-button:hover {
  background-color: #0056b3;
}
</style>
